Linked List Data Structure

This introductory guide to Linked ListData Structures, you will explore the foundational principles of Linked List, understand their significance and applications, discover effective strategies for learning, and step-by-step journey for beginners.

Overveiw

Chapters

5 Chapter are there in this module reguarding linked list data structures.

Start Learning

Quiz

Quiz on the topics being learnt in this module to ensure your knowldege.

Take Quiz

Problems

Practice Problems on the topics being covered in this module

See Problems

What is Linked List?

A linked list is a linear data structure which looks like a series of nodes, where each node has two parts: data and next pointer. Unlike arrays, linked list elements are not stored at a contiguous location. In a linked list, there is a head pointer, which points to the first element of the linked list, and if the list is empty then it simply points to null or nothing.




Basic Terminologies of Linked List

  • Head: The head of a linked list is a pointer to the first node or reference of the first node of the linked list. This pointer marks the beginning of the linked list.
  • Node: A linked list consists of a series of nodes where each node has two parts: data and next pointer.
  • Data: Data is the part of the node which stores the information in the linked list.
  • Next pointer: Next pointer is the part of the node which points to the next node of the linked list.



Importance of Linked-List

Here are a few advantages of a linked list that will help you understand why it is necessary to know:

  • Dynamic Data Structure: The size of memory can be allocated or de-allocated at run time based on the operation insertion or deletion.
  • Ease of Insertion/Deletion: The insertion and deletion of elements are simpler than arrays since no elements need to be shifted after insertion and deletion, just the address needs to be updated.
  • Efficient Memory Utilization: As we know, Linked List is a dynamic data structure; the size increases or decreases as per the requirement, so this avoids the wastage of memory.
  • Implementation: Various advanced data structures can be implemented using a linked list like a stack, queue, graph, hash maps, etc.

Types of Linked List

Types of Linked List

There are mainly three types of linked lists:

  • Singly linked list
  • Doubly linked list
  • Circular linked list



1. Singly Linked List:
Singly Linked List is a type of linked list where each node has two parts: data and next pointer. The data part stores the information and the next pointer points to the next node of the linked list. The next pointer of the last node stores null as it is the last node of the linked list and there is no next node. Traversal of items can be done in the forward direction only due to the linking of every node to its next node.

            
// Singly linked list node
class Node {
public:
    int data;
    Node* next;
};
            
          

Operations on Singly Linked List:
The following operations are performed on a Single Linked List

  • Insertion: The insertion operation can be performed in three ways. They are as follows...
    • Inserting at the Beginning of the list
    • Inserting at the End of the list
    • Inserting at a Specific location in the list
  • Deletion: The deletion operation can be performed in three ways. They are as follows...
    • Deleting from the Beginning of the list
    • Deleting from the End of the list
    • Deleting a Specific Node
  • Search: It is a process of determining and retrieving a specific node either from the front, the end, or anywhere in the list.
  • Display: This process displays the elements of a Single-linked list.



  • 2. Doubly Linked List:
    Doubly Linked List is a type of linked list where each node has three parts: data, next pointer, and previous pointer. The data part stores the information, the next pointer points to the next node of the linked list, and the previous pointer points to the previous node of the linked list. The next pointer of the last node and the previous pointer of the first node stores null. Traversal of items can be done in the forward direction as well as the backward direction due to the linking of every node to its next node as well as the previous node.

                
    /* Node of a doubly linked list */
    class Node {
    public:
        int data;
        Node* next; // Pointer to next node in DLL
        Node* prev; // Pointer to previous node in DLL
    };
                
              

    Operations on Doubly Linked List:
    In a doubly linked list, we perform the following operations…

    • Insertion: The insertion operation can be performed in three ways as follows:
      • Inserting at the Beginning of the list
      • Inserting after a given node
      • Inserting at the end
      • Inserting before a given node
    • Deletion: The deletion operation can be performed in three ways as follows...
      • Deleting from the Beginning of the list
      • Deleting from the End of the list
      • Deleting a Specific Node
    • Display: This process displays the elements of a double-linked list.



    3. Circular Linked List:
    A circular linked list is a type of linked list in which the first and the last nodes are also connected to each other to form a circle, there is no NULL at the end.

    Commonly used operations on Circular Linked List:
    The following operations are performed on a Circular Linked List

    • Insertion: The insertion operation can be performed in three ways:
      • Insertion in an empty list
      • Insertion at the beginning of the list
      • Insertion at the end of the list
      • Insertion in between the nodes
    • Deletion: The deletion operation can be performed in three ways:
      • Deleting from the Beginning of the list
      • Deleting from the End of the list
      • Deleting a Specific Node
    • Display: This process displays the elements of a Circular linked list.

Implementation of Linked List

Below is the implementation of Linked List in different languages:

C++:

// C++ program to show inserting a node
// at front of given Linked List
#include 
using namespace std;

// A linked list node
class Node {
public:
int data;
Node* next;
};

// Given a reference (pointer to pointer)
// to the head of a list and an int, inserts
// a new node on the front of the list.
void insertAtFront(Node** head_ref, int new_data)
{
// 1. allocate node
Node* new_node = new Node();

// 2. put in the data
new_node->data = new_data;

// 3. Make next of new node as head
new_node->next = (*head_ref);

// 4. move the head to point
// to the new node
(*head_ref) = new_node;
}

/* Function to remove the first node 
of the linked list */
Node* removeFirstNode(Node* head)
{
if (head == NULL)
    return NULL;

// Move the head pointer to the next node
Node* temp = head;
head = head->next;

delete temp;

return head;
}

// This function prints contents of
// linked list starting from head
void printList(Node* node)
{
while (node != NULL) {
    cout << " " << node->data;
    node = node->next;
}
cout << "\n";
}

// Driver code
int main()
{
// Start with the empty list
Node* head = NULL;

// Insert 1 at the beginning.
insertAtFront(&head, 6);
insertAtFront(&head, 5);
insertAtFront(&head, 4);
insertAtFront(&head, 3);
insertAtFront(&head, 2);
insertAtFront(&head, 1);

cout << "After inserting nodes at the front:";
printList(head);

head = removeFirstNode(head);
cout << "After removing first node:";
printList(head);

return 0;
}
        

Output:

      
After inserting nodes at the front: 1 2 3 4 5 6
After removing first node: 2 3 4 5 6
      
    

Implementation of Doubly Linked List

Insertion in a Doubly Linked List

Inserting a new node in a doubly linked list is very similar to inserting a new node in a singly linked list. There is a little extra work required to maintain the link of the previous node. A node can be inserted in a Doubly Linked List in four ways:

  • At the front of the DLL
  • In between two nodes
  • After a given node
  • Before a given node
  • At the end of the DLL



Insertion at the Beginning in Doubly Linked List:

To insert a new node at the beginning of the doubly list, we can use the following steps:

  1. Allocate memory for a new node (say new_node ) and assign the provided value to its data field.
  2. Set the previous pointer of the new_node to nullptr.
  3. If the list is empty:
    • Set the next pointer of the new_node to nullptr.
    • Update the head pointer to point to the new_node.
  4. If the list is not empty:
    • Set the next pointer of the new_node to the current head.
    • Update the previous pointer of the current head to point to the new_node.
    • Update the head pointer to point to the new_node.

Below is the implementation of the steps to insert a node at the front of the linked list:

// Given a reference (pointer to pointer) to the head 
// of a list and an int, inserts a new node 
// on the front of the list.
void push(Node** head_ref, int new_data)
{
// 1. allocate node
Node* new_node = new Node();

// 2. put in the data
new_node->data = new_data;

// 3. Make next of new node as head
// and previous as NULL
new_node->next = (*head_ref);
new_node->prev = NULL;

// 4. change prev of head node to new node
if ((*head_ref) != NULL)
  (*head_ref)->prev = new_node;

// 5. move the head to point to the new node
(*head_ref) = new_node;
}
      

Time Complexity: O(1)

Auxiliary Space: O(1)




Insertion in between two nodes in Doubly Linked List:

1. Add a node after a given node in a Doubly Linked List:
We are given a pointer to a node as prev_node, and the new node is inserted after the given node. This can be done using the following steps:

  1. Firstly create a new node (say new_node).
  2. Now insert the data in the new_node.
  3. Point the next of new_node to the next of prev_node.
  4. Point the next of prev_node to new_node.
  5. Point the previous of new_node to prev_node.
  6. Point the previous of next of new_node to new_node.

Below is the implementation of the steps to insert a node after a given node in the linked list:

// Given a node as prev_node, insert a new node 
// after the given node
void insertAfter(Node* prev_node, int new_data)
{
// Check if the given prev_node is NULL
if (prev_node == NULL) {
  cout << "the given previous node cannot be NULL";
  return;
}

// 1. allocate new node
Node* new_node = new Node();

// 2. put in the data
new_node->data = new_data;

// 3. Make next of new node as next of prev_node
new_node->next = prev_node->next;

// 4. Make the next of prev_node as new_node
prev_node->next = new_node;

// 5. Make prev_node as previous of new_node
new_node->prev = prev_node;

// 6. Change previous of new_node's next node
if (new_node->next != NULL)
  new_node->next->prev = new_node;
}
      

Time Complexity: O(1)

Auxiliary Space: O(1)




2. Add a node before a given node in a Doubly Linked List:
Let the pointer to this given node be next_node. This can be done using the following steps:

  1. Allocate memory for the new node, let it be called new_node.
  2. Put the data in new_node.
  3. Set the previous pointer of this new_node as the previous node of the next_node.
  4. Set the previous pointer of the next_node as the new_node.
  5. Set the next pointer of this new_node as the next_node.
  6. Set the next pointer of the previous of new_node to new_node.

Below is the implementation of the above approach:

// Given a node as next_node, insert a new node 
// before the given node
void insertBefore(Node* next_node, int new_data)
{
// Check if the given next_node is NULL
if (next_node == NULL) {
  printf("the given next node cannot be NULL");
  return;
}

// 1. Allocate new node
Node* new_node = new Node();

// 2. Put in the data
new_node->data = new_data;

// 3. Make previous of new node as previous of next_node
new_node->prev = next_node->prev;

// 4. Make the previous of next_node as new_node
next_node->prev = new_node;

// 5. Make next_node as next of new_node
new_node->next = next_node;

// 6. Change next of new_node's previous node
if (new_node->prev != NULL)
  new_node->prev->next = new_node;
else
  head = new_node;
}
      

Time Complexity: O(1)

Auxiliary Space: O(1)




Insertion at the End in Doubly Linked List:

The new node is always added after the last node of the given Linked List. This can be done using the following steps:

  1. Create a new node (say new_node ).
  2. Put the value in the new_node.
  3. Make the next pointer of new_node as null.
  4. If the list is empty, make new_node as the head.
  5. Otherwise, travel to the end of the linked list.
  6. Now make the next pointer of last node point to new_node.
  7. Change the previous pointer of new_node to the last node of the list.

Below is the implementation of the steps to insert a node at the end of the linked list:

// Given a reference (pointer to pointer) to the head
// of a DLL and an int, appends a new node at the end
void append(Node** head_ref, int new_data)
{
// 1. allocate node
Node* new_node = new Node();

Node* last = *head_ref; /* used in step 5*/

// 2. put in the data
new_node->data = new_data;

// 3. This new node is going to be the last node, so
// make next of it as NULL
new_node->next = NULL;

// 4. If the Linked List is empty, then make the new
// node as head
if (*head_ref == NULL) {
  new_node->prev = NULL;
  *head_ref = new_node;
  return;
}

// 5. Else traverse till the last node
while (last->next != NULL)
  last = last->next;

// 6. Change the next of last node
last->next = new_node;

// 7. Make last node as previous of new node
new_node->prev = last;

return;
}
      

Time Complexity: O(n)

Auxiliary Space: O(1)




Search in a Doubly Linked List

Given a Doubly linked list (DLL) containing N nodes and an integer X, the task is to find the position of the integer X in the doubly linked list. If no such position is found, then print -1.


Examples:

  • Input: 15 <=> 16 <=> 8 <=> 7 <=> 13, X = 8
  • Output: 3
  • Explanation: X (= 8) is present at the 3rd node of the doubly linked list. Therefore, the required output is 3.
  • Input: 5 <=> 3 <=> 4 <=> 2 <=> 9, X = 0
  • Output: -1
  • Explanation: X (= 0) is not present in the doubly linked list. Therefore, the required output is -1.



Approach:

  1. Initialize a variable, say pos, to store the position of the node containing data value X in the doubly linked list.
  2. Initialize a pointer, say temp, to store the head node of the doubly linked list.
  3. Iterate over the linked list and for every node, check if the data value of that node is equal to X or not. If found to be true, then print pos.
  4. Otherwise, print -1.

Below is the implementation of the above approach:

// C++ program to implement
// the above approach

#include 
using namespace std;

// Structure of a node of
// the doubly linked list
struct Node {
// Stores data value
// of a node
int data;

// Stores pointer
// to next node
Node* next;

// Stores pointer
// to previous node
Node* prev;
};

// Function to insert a node at the
// beginning of the Doubly Linked List
void push(Node** head_ref, int new_data)
{
// Allocate memory for new node
Node* new_node = (Node*)malloc(sizeof(struct Node));

// Insert the data
new_node->data = new_data;

// Since node is added at the
// beginning, prev is always NULL
new_node->prev = NULL;

// Link the old list to the new node
new_node->next = (*head_ref);

// If pointer to head is not NULL
if ((*head_ref) != NULL) {
// Change the prev of head
// node to new node
(*head_ref)->prev = new_node;
}

// Move the head to point to the new node
(*head_ref) = new_node;
}

// Function to find the position of
// an integer in doubly linked list
int search(Node** head_ref, int x)
{
// Stores head Node
Node* temp = *head_ref;

// Stores position of the integer
// in the doubly linked list
int pos = 0;

// Traverse the doubly linked list
while (temp->data != x && temp->next != NULL) {
// Update pos
pos++;

// Update temp
temp = temp->next;
}

// If the integer not present
// in the doubly linked list
if (temp->data != x)
return -1;

// If the integer present in
// the doubly linked list
return (pos + 1);
}

// Driver Code
int main()
{
Node* head = NULL;
int X = 8;

// Create the doubly linked list
// 18 <-> 15 <-> 8 <-> 9 <-> 14
push(&head, 14);
push(&head, 9);
push(&head, 8);
push(&head, 15);
push(&head, 18);

cout << search(&head, X);

return 0;
}
    

Output:

3


Time Complexity: O(N)

Auxiliary Space: O(1)




Delete a Node in a Doubly Linked List

Write a function to delete a given node in a doubly-linked list.


Example:

  • Input: DLL = 2->45->3->1, Node = 45
  • Output: 2->3->1
  • Input: DLL = 2->45->3->1, Node = 1
  • Output: 2->45->3

Approach:

The deletion of a node in a doubly-linked list can be divided into three main categories:

  • After the deletion of the head node.
  • After the deletion of the middle node.
  • After the deletion of the last node.

All three mentioned cases can be handled in two steps if the pointer of the node to be deleted and the head pointer is known:

  1. If the node to be deleted is the head node, then make the next node as head.
  2. If a node is deleted, connect the next and previous node of the deleted node.

Algorithm:

  • Let the node to be deleted be del.
  • If the node to be deleted is the head node, then change the head pointer to the next node.
  • if (headnode == del)
    headnode = del.nextNode
  • Set prev of next to del, if next to del exists.
  • if (del.nextNode != null)
    del.nextNode.previousNode = del.previousNode
  • Set next of prev to del, if prev to del exists.
  • if (del.previousNode != null)
    del.previousNode.nextNode = del.nextNode

Below is the implementation of the above approach:

// C++ program to delete a node from 
// Doubly Linked List 
#include <bits/stdc++.h> 
using namespace std; 

// a node of the doubly linked list 
class Node  
{  
public: 
int data;  
Node* next;  
Node* prev;  
};  

// Function to delete a node in a Doubly Linked List.  
// head_ref --> pointer to head node pointer.  
// del --> pointer to node to be deleted. 
void deleteNode(Node** head_ref, Node* del)  
{  
// base case 
if (*head_ref == NULL || del == NULL)  
return;  

// If node to be deleted is head node 
if (*head_ref == del)  
*head_ref = del->next;  

// Change next only if node to be  
// deleted is NOT the last node 
if (del->next != NULL)  
del->next->prev = del->prev;  

// Change prev only if node to be  
// deleted is NOT the first node 
if (del->prev != NULL)  
del->prev->next = del->next;  

// Finally, free the memory occupied by del 
free(del);  
return;  
}  

// UTILITY FUNCTIONS 
// Function to insert a node at the 
// beginning of the Doubly Linked List 
void push(Node** head_ref, int new_data)  
{  
// allocate node 
Node* new_node = new Node(); 

// put in the data 
new_node->data = new_data;  

// since we are adding at the beginning,  
// prev is always NULL 
new_node->prev = NULL;  

// link the old list of the new node 
new_node->next = (*head_ref);  

// change prev of head node to new node 
if ((*head_ref) != NULL)  
(*head_ref)->prev = new_node;  

// move the head to point to the new node 
(*head_ref) = new_node;  
}  

// Function to print nodes in a given doubly linked list  
// This function is same as printList() of singly linked list 
void printList(Node* node)  
{  
while (node != NULL)  
{  
cout << node->data << " ";  
node = node->next;  
}  
}  

// Driver code
int main()  
{  
// Start with the empty list 
Node* head = NULL;  

// Let us create the doubly linked list 10<->8<->4<->2 
push(&head, 2);  
push(&head, 4);  
push(&head, 8);  
push(&head, 10);  

cout << "Original Linked list ";  
printList(head);  

// delete nodes from the doubly linked list 
deleteNode(&head, head); // delete first node 
deleteNode(&head, head->next); // delete middle node 
deleteNode(&head, head->next); // delete last node 

// Modified linked list will be NULL<-8->NULL 
cout << "\nModified Linked list ";  
printList(head);  

return 0; 
}  
  

Output:

Original Linked list 10 8 4 2
Modified Linked list 8

Complexity Analysis:

Time Complexity: O(1). Since traversal of the linked list is not required so the time complexity is constant.

Auxiliary Space: O(1). As no extra space is required, so the space complexity is constant.



References:




Delete a Node in a Doubly Linked List

Write a function to delete a given node in a doubly-linked list.


Example:

  • Input: DLL = 2->45->3->1, Node = 45
  • Output: 2->3->1
  • Input: DLL = 2->45->3->1, Node = 1
  • Output: 2->45->3

Approach:

The deletion of a node in a doubly-linked list can be divided into three main categories:

  • After the deletion of the head node.
  • After the deletion of the middle node.
  • After the deletion of the last node.

All three mentioned cases can be handled in two steps if the pointer of the node to be deleted and the head pointer is known:

  1. If the node to be deleted is the head node, then make the next node as head.
  2. If a node is deleted, connect the next and previous node of the deleted node.

Algorithm:

  • Let the node to be deleted be del.
  • If the node to be deleted is the head node, then change the head pointer to the next node.
  • if (headnode == del)
    headnode = del.nextNode
  • Set prev of next to del, if next to del exists.
  • if (del.nextNode != null)
    del.nextNode.previousNode = del.previousNode
  • Set next of prev to del, if prev to del exists.
  • if (del.previousNode != null)
    del.previousNode.nextNode = del.nextNode

Below is the implementation of the above approach:

// C++ program to delete a node from 
// Doubly Linked List 
#include <bits/stdc++.h> 
using namespace std; 

// a node of the doubly linked list 
class Node  
{  
public: 
int data;  
Node* next;  
Node* prev;  
};  

// Function to delete a node in a Doubly Linked List.  
// head_ref --> pointer to head node pointer.  
// del --> pointer to node to be deleted. 
void deleteNode(Node** head_ref, Node* del)  
{  
// base case 
if (*head_ref == NULL || del == NULL)  
return;  

// If node to be deleted is head node 
if (*head_ref == del)  
*head_ref = del->next;  

// Change next only if node to be  
// deleted is NOT the last node 
if (del->next != NULL)  
del->next->prev = del->prev;  

// Change prev only if node to be  
// deleted is NOT the first node 
if (del->prev != NULL)  
del->prev->next = del->next;  

// Finally, free the memory occupied by del 
free(del);  
return;  
}  

// UTILITY FUNCTIONS 
// Function to insert a node at the 
// beginning of the Doubly Linked List 
void push(Node** head_ref, int new_data)  
{  
// allocate node 
Node* new_node = new Node(); 

// put in the data 
new_node->data = new_data;  

// since we are adding at the beginning,  
// prev is always NULL 
new_node->prev = NULL;  

// link the old list of the new node 
new_node->next = (*head_ref);  

// change prev of head node to new node 
if ((*head_ref) != NULL)  
(*head_ref)->prev = new_node;  

// move the head to point to the new node 
(*head_ref) = new_node;  
}  

// Function to print nodes in a given doubly linked list  
// This function is same as printList() of singly linked list 
void printList(Node* node)  
{  
while (node != NULL)  
{  
cout << node->data << " ";  
node = node->next;  
}  
}  

// Driver code
int main()  
{  
// Start with the empty list 
Node* head = NULL;  

// Let us create the doubly linked list 10<->8<->4<->2 
push(&head, 2);  
push(&head, 4);  
push(&head, 8);  
push(&head, 10);  

cout << "Original Linked list ";  
printList(head);  

// delete nodes from the doubly linked list 
deleteNode(&head, head); // delete first node 
deleteNode(&head, head->next); // delete middle node 
deleteNode(&head, head->next); // delete last node 

// Modified linked list will be NULL<-8->NULL 
cout << "\nModified Linked list ";  
printList(head);  

return 0; 
}  
  

Output: Original Linked list 10 8 4 2 Modified Linked list 8

Complexity Analysis:

Time Complexity: O(1). Since traversal of the linked list is not required so the time complexity is constant.

Auxiliary Space: O(1). As no extra space is required, so the space complexity is constant.



References:

Advantages, Disadvantages, and Applications Linked Lists




Advantages of Linked List:

  • Dynamic nature: Linked lists are used for dynamic memory allocation.
  • Memory efficient: Memory consumption of a linked list is efficient as its size can grow or shrink dynamically according to our requirements, which means effective memory utilization hence, no memory wastage.
  • Ease of Insertion and Deletion: Insertion and deletion of nodes are easily implemented in a linked list at any position.
  • Implementation: For the implementation of stacks and queues and for the representation of trees and graphs.
  • Constant time expansion: The linked list can be expanded in constant time.



Disadvantages of Linked List:

  • Memory usage: The use of pointers is more in linked lists hence, complex and requires more memory.
  • Accessing a node: Random access is not possible due to dynamic memory allocation.
  • Search operation costly: Searching for an element is costly and requires O(n) time complexity.
  • Traversing in reverse order: Traversing is more time-consuming and reverse traversing is not possible in singly linked lists.



Applications of Linked List:

  • Linear data structures such as stack, queue, and non-linear data structures such as hash maps, and graphs can be implemented using linked lists.
  • Dynamic memory allocation: We use a linked list of free blocks.
  • Implementation of graphs: Adjacency list representation of graphs is the most popular in that it uses linked lists to store adjacent vertices.
  • In web browsers and editors, doubly linked lists can be used to build a forwards and backward navigation button.
  • A circular doubly linked list can also be used for implementing data structures like Fibonacci heaps.